var express = require('express');
var router = express.Router();
let { isAdmin, getUserList, setUserState, userSave, userUpdate, userDelete, userAllDelete, getTypeList, typeSave, typeUpdate, typeDelete,
    typeListAll, newsList, userById, adminById, setnewsState, newsSave, newsDelete, swiperList, swiperSave, swiperUpdate, swiperDelete,
    sensitivesListAll, sensitivesSave, sensitivesDelete, adminList, adminSave, adminDelete, userCount, newsCount, newsCountToday, userWord,
    newsWord, newtypeNum
} = require('../mysql/admin');
var moment = require('moment');
const os = require('os');
let upload = require('../util/multer/index')
let { getUrlImg, FormatData } = require('../util/comm/comm.js');
let menu = require('../menu')
let config = require('../config.json')

router.post('/adminLogin', async (req, res, next) => {
    let { adminName, adminPass, code } = req.body;
    let jsonData = {};
    const sessionCaptcha = req.session.captcha.toLowerCase();
    // if (sessionCaptcha != code) {
    //     return res.json({
    //         flog: 0,
    //         data: '验证码不正确'
    //     });
    // }
    let data = await isAdmin({
        adminName, adminPass
    })
    if (!data.length) {
        jsonData = {
            code: 0,
            data: "账号或者密码错误",
        }
    } else {
        jsonData = {
            code: 1,
            data: data[0]
        }
        req.session.adminInfo = data[0]
    }
    return res.json(jsonData)
});

router.get('/menu', async (req, res, next) => {
    res.json({
        code: 1,
        menu
    })
});

router.post('/userList', async (req, res, next) => {
    let { page, limit, userId, userName, userState } = req.body;
    var num = (page - 1) * limit;
    let { data, count } = await getUserList(num, limit, {
        userId, userName, userState
    });
    if (data.length) {
        res.json({
            code: 1,
            data: data,
            count: count
        })
    } else {
        res.json({
            code: 0,
            msg: "数据加载完毕",
            count: count
        })
    }

});

router.post('/userState', async (req, res, next) => {
    let { userId, userState } = req.body;
    let { affectedRows } = await setUserState(userId, {
        userState
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: "修改失败 "
        })
    }
})

router.post('/userSave', async (req, res, next) => {
    let { userName, userUrl, userSex, userIntegral, userPass } = req.body;
    let { affectedRows } = await userSave({
        userName, userUrl, userSex, userIntegral, userPass
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '添加失败'
        })
    }
})

router.post('/userUpdate', async (req, res, next) => {
    let { userName, userUrl, userSex, userIntegral, userId, userPass } = req.body;
    let { affectedRows } = await userUpdate(userId, {
        userName, userUrl, userSex, userIntegral, userPass
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '修改失败'
        })
    }
})

router.post('/userDelete', async (req, res, next) => {
    let { userId } = req.body;
    let { affectedRows } = await userDelete(userId)
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '删除失败'
        })
    }
})

router.post('/resetpwd', async (req, res, next) => {
    let { userId } = req.body;
    let { affectedRows } = await userUpdate(userId, {
        userPass: config.resetpwd_userPass
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '重置失败'
        })
    }
})

router.post('/userAllDelete', async (req, res, next) => {
    let { userIdList } = req.body;
    let { affectedRows } = await userAllDelete(userIdList)
    if (affectedRows) {
        next({
            code: 1
        })
    } else {
        next({
            code: 0,
            msg: '删除失败'
        })
    }
})

router.post('/loginout', async (req, res, next) => {
    delete req.session.adminInfo;
    next({
        code: 1
    })
})

router.post('/typeList', async (req, res, next) => {
    let { page, limit, typeName } = req.body;
    var num = (page - 1) * limit;
    let { data, count } = await getTypeList(num, limit, {
        typeName
    });
    if (data.length) {
        res.json({
            code: 1,
            data: data,
            count: count
        })
    } else {
        res.json({
            code: 0,
            msg: "数据加载完毕",
            count: count
        })
    }

});

router.post('/typeListAll', async (req, res, next) => {
    let { data, count } = await typeListAll();
    if (data.length) {
        res.json({
            code: 1,
            data: data,
            count: count
        })
    } else {
        res.json({
            code: 0,
            msg: "数据加载完毕",
            count: count
        })
    }
});

router.post('/typeSave', async (req, res, next) => {
    let { typeName } = req.body;
    let { affectedRows } = await typeSave({
        typeName
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '添加失败'
        })
    }
})

router.post('/typeUpdate', async (req, res, next) => {
    let { typeName, typeId } = req.body;
    let { affectedRows } = await typeUpdate(typeId, {
        typeName
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '修改失败'
        })
    }
})

router.post('/typeDelete', async (req, res, next) => {
    let { typeId } = req.body;
    let { affectedRows } = await typeDelete(typeId)
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '删除失败'
        })
    }
})

router.post('/newsList', async (req, res, next) => {
    let { page, limit, newsId, newsTitle, newsType } = req.body;
    var num = (page - 1) * limit;
    let { data, count } = await newsList(num, limit, {
        newsId, newsTitle, newsType
    });

    await new Promise(async (resolve, reject) => {
        let promiseList = data.map((item) => {
            return new Promise(async (res, rej) => {
                if (item.userIdentity == 'admin') {
                    let [{ adminName }] = await adminById(item.userId)
                    item.userName = adminName
                } else {
                    let [{ userName }] = await userById(item.userId)
                    item.userName = userName
                }
                res()
            })
        })
        await Promise.all(promiseList)
        resolve()
    })

    if (data.length) {
        res.json({
            code: 1,
            data: FormatData(data, {
                newsImg: 'json'
            }),
            count: count
        })
    } else {
        res.json({
            code: 0,
            msg: "数据加载完毕",
            count: count
        })
    }

});

router.post('/newsState', async (req, res, next) => {
    let { newsId, newsState } = req.body;
    let { affectedRows } = await setnewsState(newsId, {
        newsState
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: "修改失败 "
        })
    }
})

router.post('/newsSave', async (req, res, next) => {
    let { userId, userIdentity, newsState, newsTitle, newsType, newsCollection, newsIntegral, newsWatch, newsTime, newContent, newsImg } = req.body;
    userId = req.session.adminInfo.adminId
    userIdentity = 'admin'
    newsState = '1'
    newsImg = JSON.stringify(newsImg)
    let { affectedRows } = await newsSave({
        userId, userIdentity, newsState, newsTitle, newsType, newsCollection, newsIntegral, newsWatch, newsTime, newContent, newsImg
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '添加失败'
        })
    }
})

router.post('/newsDelete', async (req, res, next) => {
    let { newsId } = req.body;
    let { affectedRows } = await newsDelete(newsId)
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '删除失败'
        })
    }
})

router.post('/swiperList', async (req, res, next) => {
    let { page, limit } = req.body;
    var num = (page - 1) * limit;
    let { data, count } = await swiperList(num, limit, {});
    if (data.length) {
        res.json({
            code: 1,
            data: data,
            count: count
        })
    } else {
        res.json({
            code: 0,
            msg: "数据加载完毕",
            count: count
        })
    }

});

router.post('/swiperSave', async (req, res, next) => {
    let { swiperurl, swiperIndex } = req.body;
    let { affectedRows } = await swiperSave({
        swiperurl, swiperIndex
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '添加失败'
        })
    }
})

router.post('/swiperUpdate', async (req, res, next) => {
    let { swiperurl, swiperIndex, swiperId } = req.body;
    let { affectedRows } = await swiperUpdate(swiperId, {
        swiperurl, swiperIndex
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '修改失败'
        })
    }
})

router.post('/swiperDelete', async (req, res, next) => {
    let { swiperId } = req.body;
    let { affectedRows } = await swiperDelete(swiperId)
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '删除失败'
        })
    }
})

router.post('/sensitivesListAll', async (req, res, next) => {
    let { data, count } = await sensitivesListAll();
    if (data.length) {
        res.json({
            code: 1,
            data: data,
            count: count
        })
    } else {
        res.json({
            code: 0,
            msg: "数据加载完毕",
            count: count
        })
    }
});

router.post('/sensitivesSave', async (req, res, next) => {
    let { sensitiveTag } = req.body;
    let { insertId, affectedRows } = await sensitivesSave({
        sensitiveTag
    })
    if (affectedRows) {
        res.json({
            code: 1,
            data: {
                sensitiveId: insertId,
                sensitiveTag: sensitiveTag
            }
        })
    } else {
        res.json({
            code: 0,
            msg: '添加失败'
        })
    }
})

router.post('/sensitivesDelete', async (req, res, next) => {
    let { sensitiveId } = req.body;
    let { affectedRows } = await sensitivesDelete(sensitiveId)
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '删除失败'
        })
    }
})

router.post('/swiperSave', async (req, res, next) => {
    let { swiperurl, swiperIndex } = req.body;
    let { affectedRows } = await swiperSave({
        swiperurl, swiperIndex
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '添加失败'
        })
    }
})

router.post('/swiperUpdate', async (req, res, next) => {
    let { swiperurl, swiperIndex, swiperId } = req.body;
    let { affectedRows } = await swiperUpdate(swiperId, {
        swiperurl, swiperIndex
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '修改失败'
        })
    }
})

router.post('/swiperDelete', async (req, res, next) => {
    let { swiperId } = req.body;
    let { affectedRows } = await swiperDelete(swiperId)
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '删除失败'
        })
    }
})

router.post('/adminList', async (req, res, next) => {
    let { page, limit, adminId } = req.body;
    var num = (page - 1) * limit;
    let { data, count } = await adminList(num, limit, { adminId });
    if (data.length) {
        res.json({
            code: 1,
            data: data,
            count: count
        })
    } else {
        res.json({
            code: 0,
            msg: "数据加载完毕",
            count: count
        })
    }

});

router.post('/adminSave', async (req, res, next) => {
    let { adminName, adminPass, adminEmail } = req.body;
    let { affectedRows } = await adminSave({
        adminName, adminPass, adminEmail
    })
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '添加失败'
        })
    }
})

router.post('/adminDelete', async (req, res, next) => {
    let { adminId } = req.body;
    let { affectedRows } = await adminDelete(adminId)
    if (affectedRows) {
        res.json({
            code: 1
        })
    } else {
        res.json({
            code: 0,
            msg: '删除失败'
        })
    }
})

router.post('/uploadImg', upload.single('file'), async (req, res, next) => {
    let url = getUrlImg(req);
    res.json({
        code: 200,
        data: { url: url },
        url: url,
        msg: "success"
    })
})

router.post('/swiperuploadImg', upload.single('file'), async (req, res, next) => {
    let url = getUrlImg(req);
    res.json({
        code: 200,
        data: { url: url },
        url: url,
        msg: "success"
    })
})

router.post('/countData', async (req, res, next) => {
    let userNumCount = await userCount()
    let newsNumCount = await newsCount();
    let newsNumCountToday = await newsCountToday()
    let userNumLine = await new Promise((res, rej) => {
        req.sessionStore.all(function (err, sessions) {
            let sessionList = Object.values(sessions)
            if (sessionList.length) {
                res(sessionList.filter(item => item.userInfo).length)
            } else {
                res(0)
            }
        })
    })
    res.json({
        code: 1,
        data: {
            userNumCount, newsNumCount, newsNumCountToday: newsNumCountToday, userNumLine: userNumLine
        }
    })
})

router.post('/userWord', async (req, res, next) => {
    let DayList = [];
    for (var i = 1; i <= 7; i++) {
        DayList.push(moment().isoWeekday(i))
    }
    let { count, data } = await userWord();
    let userNum = []
    DayList.forEach(dayItem => {
        let sunNum = 0;
        data.forEach(item => {
            if (dayItem.isSame(item.userTime, 'day')) {
                sunNum++;
            }
        })
        userNum.push(sunNum)
    })

    res.json({
        code: 1,
        userNum: userNum,
        count: count
    })
});

router.post('/newsWord', async (req, res, next) => {
    let DayList = [];
    for (var i = 1; i <= 7; i++) {
        DayList.push(moment().isoWeekday(i))
    }
    let { count, data } = await newsWord();
    let newsNum = []
    DayList.forEach(dayItem => {
        let sunNum = 0;
        data.forEach(item => {
            if (dayItem.isSame(item.newsTime, 'day')) {
                sunNum++;
            }
        })
        newsNum.push(sunNum)
    })

    res.json({
        code: 1,
        newsNum: newsNum,
        count: count
    })
});

router.post('/newtypeNum', async (req, res, next) => {
    let typeList = await typeListAll();
    typeList = typeList.data.map(item => item.typeName)
    let data = await newtypeNum(typeList);
    data = JSON.parse(JSON.stringify(data))
    data = data.map(item => {
        return item[0]
    })
    console.log(typeList)
    res.json({
        code: 1,
        typeList: typeList,
        newtypeNum: data
    })
})

router.post('/getCpuTable', async (req, res, next) => {
    var freeMem = os.freemem() / 1024 / 1024 / 1024;
    var totalMem = os.totalmem() / 1024 / 1024 / 1024;
    res.json({
        code: 1,
        CpuNum: ((freeMem) / totalMem * 100.0).toFixed(2)
    })
})

router.use((info, req, res, next) => {
    if (info.code) {
        res.json({
            code: 1,
            data: info.data || null
        })
    } else {
        res.json({
            code: 0,
            msg: info.msg || ''
        })
    }
})

module.exports = router;
